﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WMS_Goodsinfo.Api.Read.Application.Command;
using WMS_Goodsinfo.Api.Read.DTOS;
using WMS_Goodsinfo.Domain;
using WMS_Goodsinfo.ErrorCode;
using WMS_Goodsinfo.Infastructure;

namespace WMS_Goodsinfo.Api.Read.Application.Handler
{
    public class SelectInoutListHandler : IRequestHandler<SelectInoutListCommand, ApiPaging<InOutListDto>>
    {
        private readonly IProductRepository<InOut> _inoutRepo;//出入表
        private readonly IProductRepository<Product_Table> _productRepo;//货品表

        public SelectInoutListHandler(IProductRepository<InOut> inoutRepo, IProductRepository<Product_Table> productRepo)
        {
            _inoutRepo = inoutRepo;
            _productRepo = productRepo;
        }
        /// <summary>
        /// 查询出入库流水列表（支持分页和过滤）
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页出入库流水列表</returns>
        public async Task<ApiPaging<InOutListDto>> Handle(SelectInoutListCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<InOutListDto>();
            
            try
            {
                // 基础查询：获取未删除的出入库记录
                var inout = _inoutRepo.GetAll().Where(p => !p.IsDelete);
                var product = _productRepo.GetAll().Where(p => !p.IsDelete);

                // 应用过滤条件
                if (request.ProductId.HasValue)
                {
                    inout = inout.Where(i => i.ProductI_Id == request.ProductId.Value);
                }

                if (!string.IsNullOrWhiteSpace(request.InOutNo))
                {
                    inout = inout.Where(i => i.InOutNo.Contains(request.InOutNo));
                }

                if (!string.IsNullOrWhiteSpace(request.BusinessType))
                {
                    inout = inout.Where(i => i.BusinessType == request.BusinessType);
                }

                if (!string.IsNullOrWhiteSpace(request.InOutType))
                {
                    inout = inout.Where(i => i.InOutType == request.InOutType);
                }

                if (!string.IsNullOrWhiteSpace(request.InOutTiem))
                {
                    inout = inout.Where(i => i.InOutTiem.Contains(request.InOutTiem));
                }

                if (request.CreateTime.HasValue)
                {
                    inout = inout.Where(i => i.CreateTime.Value.Date == request.CreateTime.Value.Date);
                }

                // 联表查询
                var query = from i in inout
                            join p in product on i.ProductI_Id equals p.Id
                            select new InOutListDto
                            {

                                ProductI_Id = i.ProductI_Id,
                                ProductNo=p.ProductNo,
                                ProductName=p.ProductName,
                                ProductTypeId=p.ProductTypeId,
                                ProductModel=p.ProductModel,
                                UnitName=p.UnitName,
                                InOutNo = i.InOutNo,
                                InOutTiem = i.InOutTiem,
                                BusinessType = i.BusinessType,
                                InOutType = i.InOutType,
                                Inventory = p.Inventory, // 从货品表获取仓库名称
                                InNumber = i.InNumber,
                                OutNumbber = i.OutNumbber,
                                InMoney = i.InMoney,
                                OutMoney = i.OutMoney,
                                Batch_Id = i.Batch_Id,
                                CreateTime = i.CreateTime,
                                Createer = i.Createer
                            };

                // 应用仓库过滤条件（需要在联表后进行）
                if (!string.IsNullOrWhiteSpace(request.Inventory))
                {
                    query = query.Where(q => q.Inventory == request.Inventory);
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);
                
                // 计算总页数
                var totalPage = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 应用分页和排序
                var inoutList = await query
                    .OrderByDescending(q => q.CreateTime) // 按创建时间倒序
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 设置返回结果
                result.Code = StatusEnum.OK;
                result.Message = "查询成功";
                result.TotalCount = totalCount;
                result.TotalPage = totalPage;
                result.PageData = inoutList;
            }
            catch (Exception ex)
            {
                result.Code = StatusEnum.Error;
                result.Message = $"查询失败: {ex.Message}";
                result.TotalCount = 0;
                result.TotalPage = 0;
                result.PageData = new List<InOutListDto>();
            }

            return result;
        }
    }
}
